﻿package ray.wx.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ray.wx.util.*;

/**
 * Servlet implementation class CoreServlet
 */
@WebServlet("/CoreServlet")
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private MysqlUtil m_mysql;
	
    /**
     * Default constructor. 
     */
    public CoreServlet() {
        // TODO Auto-generated constructor stub
    }
    
    public void init() throws ServletException {  
    	m_mysql = new MysqlUtil("jdbc:mysql://192.168.231.137:3306/weixin", "root", "root123");
        
    	try {
			m_mysql.connect();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServletException("Database init failed!");
		}
    }  

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
        // my  
        // ΢�ż���ǩ��  		
        String signature = request.getParameter("signature");  
        // ʱ��¾  
        String timestamp = request.getParameter("timestamp");  
        // �����  
        String nonce = request.getParameter("nonce");  
        // ����ַ�  
        String echostr = request.getParameter("echostr");   
          
        PrintWriter out = response.getWriter();  
        // ͨ����� signature ���������У�飬��У��ɹ���ԭ��� echostr����ʾ����ɹ����������ʧ��  
       if(SignUtil.checkSignature(signature, timestamp, nonce)){  
           out.print(echostr);  
       }  
  
       out.close();  
       out = null;   		
		
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		XMLUtil xmlParse = new XMLUtil();

		xmlParse.init(request.getInputStream());
		int num = xmlParse.locateParent("xml");
		
		for (int i = 0; i < num; i++){
			String msgType = xmlParse.getValueByName("MsgType");
			if (msgType.equals("text")){
				String to_user = xmlParse.getValueByName("ToUserName");
				String from_user =  xmlParse.getValueByName("FromUserName");
				String create_time = xmlParse.getValueByName("CreateTime");
				String content = xmlParse.getValueByName("Content");
				String msg_id = xmlParse.getValueByName("MsgId");
				
				String sql = "select count(*) from msg_from_user where msg_id = " + msg_id + ";";
				int count = m_mysql.get_record_count(sql);
				if (count == -1){
				    return;
				} else if (count == 0){
					String local_time = MysqlUtil.get_cur_timestamp();
			        sql = "insert into msg_from_user (to_user_name, from_user_name, create_time, msg_type, content, msg_id, update_time) values ('" + to_user + "', '" + from_user + "', " + create_time + ", '" + msgType + "', '" + content + "', " + msg_id + ", " + local_time+ ");";
			        m_mysql.update_db(sql);				    
				}
				
/*				
				XMLUtil xmlMake = new XMLUtil();
				xmlMake.init();
				xmlMake.startParent("xml");
				xmlMake.appendChild("ToUserName", "![CDATA[" + from_user + "]]");
				xmlMake.appendChild("FromUserName", "![CDATA[" + to_user + "]]");
				Date now = new Date();
				long time_t = now.getTime();
				String str_time = time_t + "";
				xmlMake.appendChild("CreateTime", str_time);
				xmlMake.appendChild("MsgType", "![CDATA[text]]");
				xmlMake.appendChild("Content", "![CDATA[hello]]");
				String xmlText = xmlMake.endParent();
*/				
				PrintWriter out = response.getWriter();
				out.print("");
				
			    out.close();  
			    out = null;				
			}
		}
	}

}
